/* 
 * File:   indicator.c
 * Author: Marcel
 *
 * Created on 12. September 2012, 03:30
 */

#include <p18f2620.h>
#include <timers.h>
#include "interrupt.h"
#include "timer.h"
#include "indicator.h"

// Global variables
extern unsigned char heater_active;
unsigned char beeper_active;
unsigned int beeper_time = 0;

void idctr_isr(void) {
    INTCONbits.GIEL = 0;    // Enable all low priority interrupts
    TMR2 = 125;
    PR2 = 0xFF;
    
    //LATC ^= 0b00001000;
    INTCONbits.GIEL = 1;    // Enable all low priority interrupts
}

/* The value of reps is a multiplicator for the beep duration.
 * Max value for time_l and time_h is 252.
 */
void idctr_beep(unsigned char reps, unsigned int time) {
    beeper_active = reps;
    beeper_time = time;
}

void idctr_heater(unsigned char state) {
    heater_active = state;
}

void idctr_work(void) {
    static unsigned int beep_time_ctr = 0, nobeep_time_ctr = 0;
    if(heater_active) {
        //if(timer_500ms())
           // LATC ^= 0b00000100;
    }

    if(beeper_active) {
        if(beep_time_ctr < beeper_time) {
            LATC ^= 0b00001000;
            beep_time_ctr++;
            nobeep_time_ctr = 0;
        }
        else {
            if(nobeep_time_ctr >= 1000) {
                beep_time_ctr = 0;
                beeper_active--;
            }
            nobeep_time_ctr++;
        }
    }
}

void idctr_init(void) {
    TRISCbits.TRISC1 = 0;   // Power LED -> out
    TRISCbits.TRISC2 = 0;   // Heater LED -> out
    TRISCbits.TRISC3 = 0;   // Beeper -> out

    LATCbits.LATC1 = 0; // Power LED -> on
    LATCbits.LATC2 = 0; // Heater LED -> off
    LATCbits.LATC3 = 0; // Beeper -> low

    //idctr_timer_init();
}

/* Timer 0 - 8bit
 * 976.56 Overflows/sec */
void idctr_timer_init(void) {
    OpenTimer2(TIMER_INT_ON &
               T2_PS_1_16 &
               T2_POST_1_1);

    IPR1bits.TMR2IP = 0;
    TMR2 = 125;
    PR2 = 0xFF;
}